package stack

import "strconv"

// https://leetcode.cn/problems/evaluate-reverse-polish-notation leetcode-150
func evalRPN(tokens []string) int {
	isOp := func(val string) bool {
		return val == "+" || val == "-" || val == "*" || val == "/"
	}

	m := make(map[string]func(a, b int32) int32)
	m["+"] = func(a, b int32) int32 { return a + b }
	m["-"] = func(a, b int32) int32 { return a - b }
	m["*"] = func(a, b int32) int32 { return a * b }
	m["/"] = func(a, b int32) int32 { return a / b }

	stack := make([]int32, (len(tokens)+1)/2)
	index := -1
	for _, s := range tokens {
		if isOp(s) {
			num1 := stack[index-1]
			num2 := stack[index]
			index--
			stack[index] = m[s](num1, num2)
		} else {
			index++
			stack[index] = stringToInt32(s)
		}
	}
	return int(stack[index])
}

func stringToInt32(s string) int32 {
	i, _ := strconv.ParseInt(s, 10, 64)
	return int32(i)
}
